package com.api.shopapi.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.excel.EasyExcel;
import com.api.shopapi.entity.MyResult;
import com.api.shopapi.entity.PreCheck;
import com.api.shopapi.service.ElderlyService;
import com.api.shopapi.service.ImportExcelService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RequestMapping("ImportExcel")
@RestController
public class ImportExcelController extends BaseController {


    @Autowired
    @Qualifier("ImportExcelServiceImplOne")
    private ImportExcelService importExcelService;

    @Autowired
    @Qualifier("ElderlyServiceImplOne")
    private ElderlyService elderlyService;

    @Value("${my.thread}")
    protected String path;

    @Value("${my.filesRootPath}")
    protected String filesRootPath;

    @RequestMapping(value = "Import", method = RequestMethod.POST)
    public MyResult Import(@RequestParam("file") MultipartFile file,
                           @RequestParam("timeStr") String timeStr,
                           @RequestParam("sign") String sign,
                           @RequestParam("staffCode") String staffCode) {


        JSONObject jsonObject = new JSONObject();
        try {

            String uuid = UUID.randomUUID().toString();

            jsonObject.put("file",file);
            jsonObject.put("staffCode",staffCode);

            PreCheck preCheck =checkSignAdmInterface(timeStr, sign,staffCode,"/ImportExcel/Import");
            if(preCheck.getError()==1){
                return failed(preCheck.getMessage());
            }

            if (file.isEmpty()) {
                return failed("文件不存在");
            }
            String fileName = file.getOriginalFilename();
            if(!isFile(fileName)){
                return failed("非正确的文件格式不能上传");
            }
            String suffix = getSuffix(fileName);
            File filesPath =new File(filesRootPath);
            if(!filesPath.exists()){
                filesPath.mkdir();
            }
            String fdPath = filesRootPath+"\\"+staffCode;
            File fd =new File(fdPath);
            if(!fd.exists()){
                fd.mkdir();
            }

            String filePath11 = fdPath + "\\" +  getTimeStr() + suffix;
            File dest =new File(filePath11);
            try {
                file.transferTo(dest);
            } catch (Exception e) {
                return failed("上传失败:"+e.getMessage());
            }


            String message1="";
            Thread t =new Thread(new Runnable() {
                @Override
                public void run() {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


                    try {
                        File file1 = new File(path);
                        if (!file1.exists()) {//如果文件夹不存在
                            file1.mkdir();//创建文件夹
                        }
                        System.out.println("path = " + path);
                        String filePath = path +"\\"+ uuid + ".txt";
                        System.out.println("写入0");
                        String content1 = "0";
                        saveAsFileWriter(filePath, content1);
                        System.out.println("写入完成");

                        String content2="3";
                        String message="";

                        try {
                            MultipartFile file2 = getMulFileByPath(filePath11);
                            InputStream is = file2.getInputStream();
                            System.out.println("1---------------------" + sdf.format(new Date()));
                            String fileName = file.getOriginalFilename();

                            //MyResult myResult = importExcelService.batchImport(fileName, file, staffCode,is);

                            MyResult myResult = importExcelService.batchImportNew(fileName, file, staffCode,is);

                            System.out.println("2----------------------" + sdf.format(new Date()));
                            if(myResult.getError()==0){
                                System.out.println("3----------------------"+sdf.format(new Date()));
                                System.out.println("写入1");
                                String content3 = "1";
                                saveAsFileWriter(filePath, content3);
                                System.out.println("写入完成");
                            }else if(myResult.getError()==1){
                                content2 = myResult.getMessage();
                                saveAsFileWriter(filePath, content2);
                            }

                            System.out.println("content2 = " + content2);

                        } catch (Exception e) {
                            System.out.println("写入2");
                            content2 = "2";
                            insertError("/ImportExcel/Import", "file", getExceptionMsg(e), "api");
                            saveAsFileWriter(filePath, content2);
                            System.out.println("写入完成");
                        }

                    } catch (Exception e) {
                        insertError("/ImportExcel/Import", "file", getExceptionMsg(e), "api");
                        System.out.println("批量导入失败");
                    }

                }
            });
            t.start();

//            String fileName = file.getOriginalFilename();
//            MyResult myResult = importExcelService.batchImport(fileName, file, staffCode);

            return success(uuid);

        } catch (Exception e) {
            insertErrorForAffair("/ImportExcel/Import", jsonObject, e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return anomalous(e.getMessage());
        }
    }


    @RequestMapping(value = "IsSuccess", method = RequestMethod.POST)
    public MyResult IsSuccess(@RequestBody JSONObject jsonObject) {

        String uuid = jsonObject.getString("uuid");
        try {
            StringBuffer buffer = new StringBuffer();
            BufferedReader bf = new BufferedReader(new FileReader(path+"\\" + uuid + ".txt"));
            String s = null;
            while ((s = bf.readLine()) != null) {//使用readLine方法，一次读一行
                buffer.append(s.trim());
            }
            bf.close();
            String b = buffer.toString();
            if(b.equals("1")){
                File file = new File(path+"\\" + uuid + ".txt");
                file.delete();
            }

            return success(b);
        } catch (IOException e) {
            insertError("/ImportExcel/IsSuccess", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }

    }


    @Value("${my.templates.importElderly}")
    protected String importElderly;


    //老人模板表下载
    @RequestMapping(value = "GetElderlyTemplate", method = RequestMethod.GET)
    public MyResult GetElderlyTemplate(@RequestParam("timeStr") String timeStr,
                                       @RequestParam("sign") String sign,
                                       @RequestParam("staffCode") String staffCode,
                                       HttpServletResponse response) {

        try {

            PreCheck preCheck =checkSignAdmInterface(timeStr, sign,staffCode,"/ImportExcel/GetElderlyTemplate");
            if(preCheck.getError()==1){
                return failed(preCheck.getMessage());
            }

            ClassPathResource classPathResource = new ClassPathResource(importElderly);
            InputStream inputStream = classPathResource.getInputStream();
            File somethingFile = File.createTempFile("老人模板下载", ".xlsx");
            FileUtils.copyInputStreamToFile(inputStream, somethingFile);
            String templateFileName = somethingFile.getAbsolutePath();
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("服务对象模板下载", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream()).withTemplate(templateFileName).sheet().doWrite(null);

            JSONObject jsonObject = new JSONObject();
            return success(jsonObject);
        } catch (Exception e) {
            return anomalous(getExceptionMsg(e));
        }
    }



    private static MultipartFile getMulFileByPath(String picPath) {
        FileItem fileItem = createFileItem(picPath);
        MultipartFile mfile = new CommonsMultipartFile(fileItem);
        return mfile;
    }

    private static FileItem createFileItem(String filePath) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        String textFieldName = "textField";
        int num = filePath.lastIndexOf(".");
        String extFile = filePath.substring(num);
        FileItem item = factory.createItem(textFieldName, "text/plain", true,
                "MyFileName" + extFile);
        File newfile = new File(filePath);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try
        {
            FileInputStream fis = new FileInputStream(newfile);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192))
                    != -1)
            {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return item;
    }


    @RequestMapping(value = "RechargeImport", method = RequestMethod.POST)
    public MyResult RechargeImport(@RequestParam("file") MultipartFile file,
                                   @RequestParam("timeStr") String timeStr,
                                   @RequestParam("sign") String sign,
                                   @RequestParam("staffCode") String staffCode) {

        JSONObject jsonObject = new JSONObject();
        try {
            String uuid = UUID.randomUUID().toString();

            jsonObject.put("file", file);
            jsonObject.put("staffCode", staffCode);

            if (file.isEmpty()) {
                return failed("文件不存在");
            }
            String fileName = file.getOriginalFilename();
            if(!isFile(fileName)){
                return failed("非正确的文件格式不能上传");
            }
            String suffix = getSuffix(fileName);
            String fdPath = filesRootPath+"\\"+staffCode;
            File fd =new File(fdPath);
            if(!fd.exists()){
                fd.mkdir();
            }
            String filePath11 = fdPath + "\\" +  getTimeStr() + suffix;
            File dest =new File(filePath11);
            try {
                file.transferTo(dest);
            } catch (Exception e) {
                return failed("上传失败:"+e.getMessage());
            }
            String message1="";
            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


                    try {
                        File file1 = new File(path);
                        if (!file1.exists()) {//如果文件夹不存在
                            file1.mkdir();//创建文件夹
                        }
                        System.out.println("path = " + path);
                        String filePath = path +"\\"+ uuid + ".txt";
                        System.out.println("写入0");
                        String content1 = "0";
                        saveAsFileWriter(filePath, content1);
                        System.out.println("写入完成");

                        String content2="3";
                        String message="";
                        try {
                            MultipartFile file2 = getMulFileByPath(filePath11);
                            InputStream is = file2.getInputStream();
                            System.out.println("1---------------------" + sdf.format(new Date()));
                            String fileName = file.getOriginalFilename();
                            MyResult myResult =importExcelService.batchRechargeImport(fileName, file, staffCode, is);
                            System.out.println("2----------------------" + sdf.format(new Date()));
                            if(myResult.getError()==0){
                                System.out.println("3----------------------"+sdf.format(new Date()));
                                System.out.println("写入1");
                                String content3 = "1";
                                saveAsFileWriter(filePath, content3);
                                System.out.println("写入完成");
                            }else if(myResult.getError()==1){
                                content2 = myResult.getMessage();
                                saveAsFileWriter(filePath, content2);
                            }

                            System.out.println("content2 = " + content2);

                        } catch (Exception e) {
                            e.printStackTrace();
                            System.out.println("写入2");
                            content2 = "2";
                            saveAsFileWriter(filePath, content2);
                            System.out.println("写入完成");
                        }






                    } catch (Exception e) {
                        //                    insertError("/Goods/Add", jsonObject.toJSONString(), getExceptionMsg(e), "api");
                        System.out.println("批量充值失败");
                    }
                }
            });
            t.start();
            return success(uuid);
        } catch (Exception e) {
            insertErrorForAffair("/ImportExcel/RechargeImport", jsonObject, e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return anomalous(getExceptionMsg(e));
        }

    }

}
